<?php
error_reporting(7);
#set_error_handler("error");

$config = config();

function config()
   {
   global $configdb;
   $config = array();
   $abfrage = "SELECT `feld`,`wert` FROM `$configdb`";
   $ergebnis = mysql_query($abfrage);
   while($row = mysql_fetch_row($ergebnis))
      $config[$row[0]] = $row[1];

   return $config;
   }


// >>> Nur fuer die Entwicklung benutzen!! <<<
function error($errno, $errstr, $errfile, $errline) {
$err=array(1 => 'E_ERROR' , 2 => 'E_WARNING' , 4 => 'E_PARSE' , 8 => 'E_NOTICE', 2048 => 'E_STRICT');
if(!eregi("^(Undefined index|Undefined offset)",$errstr))
   {
   echo "<b>$err[$errno]:</b><br>
   <b>Datei:</b> ".basename($errfile)." ($errline)<br>
   <b>Fehler:</b> $errstr<br><br>";
    }
}



function check($seite,$rights)
   {
   $seite = basename($seite);

   if($rights === NULL)
      return true;

   global $rights_files;

   if(!isset($rights_files[$seite]))
      return false;

   if( ($rights&$rights_files[$seite]) > 0)
      return true;

   return false;
   }


function menu($rights)
   {
   $menu = "";
   if(check("verwalten.php",$rights))
      $menu .= "<a href=\"verwalten.php\">Emails verwalten</a><br>";

   if(check("write.php",$rights))
      $menu .= "<a href=\"write.php\">Newsletter schreiben</a><br>";

   if(check("einstellungen.php",$rights))
      $menu .= "<a href=\"einstellungen.php\">Einstellungen</a><br>";

   if(check("automails.php",$rights))
      $menu .= "<a href=\"automails.php\">Automatische Emails</a><br>";

   if(check("design.php",$rights))
      $menu .= "<a href=\"design.php\">Design anpassen</a><br>";

   if(check("export.php",$rights))
      $menu .= "<a href=\"export.php\">Emails importieren/exportieren</a><br>";

   if(check("user.php",$rights))
      $menu .= "<a href=\"user.php\">Benutzer verwalten</a><br>";

   $menu .= '<br><a href="pwchange.php">Passwort &auml;ndern</a><br>
<a href="index.php?was=logout">Logout</a><br><br>';

   return $menu;
   }





function send_eintragen($email,$name)
   {
   global $textdb,$config;

   if($config['auto_eintrag'] == "1")
      { 
      $abfrage = "SELECT * FROM `$textdb` WHERE `name` = 'eintragen'";
      $ergebnis = mysql_query($abfrage);
      $row = mysql_fetch_object($ergebnis);

      $text = eregi_replace("\{(name|alias)\}",$name,$row->text);
      $betreff = $row->betreff;

      $from = "From: ".$config['name']." <".$config['email'].">\n";

      if($config['email_antwort'] != "")
         $from .= "Reply-To: ".$config['email_antwort']."\n";

      $from .= "Message-ID: <".md5(uniqid(time()))."@".$_SERVER['SERVER_NAME'].">\n";

      ($row->modus == "html") ? $from .= "Content-Type: text/html\n" : $from .= "Content-type: text/plain; charset=iso-8859-1\nContent-transfer-encoding: 8bit\n";

      $from .= "Date: ".date('r', time())."\n";
      $from .= "X-Priority: 3\n";
      $from .= "X-MSMail-Priority: Normal\nX-Mailer: PHP\nX-MimeOLE: Produced By Clanletter\n";

      return sendmail($email, $betreff, $text, $from);
      }
   }

function send_austragen($email)
   {
   global $textdb,$config;

   if($config['auto_austrag'] == "1")
      {
      $abfrage = "SELECT * FROM `$textdb` WHERE `name` = 'austragen'";
      $ergebnis = mysql_query($abfrage);
      $row = mysql_fetch_object($ergebnis);

      $text = $row->text;
      $betreff = $row->betreff;

      $from = "From: ".$config['name']." <".$config['email'].">\n";

      if($config['email_antwort'] != "")
         $from .= "Reply-To: ".$config['email_antwort']."\n";

      $from .= "Message-ID: <".md5(uniqid(time()))."@".$_SERVER['SERVER_NAME'].">\n";

      ($row->modus == "html") ? $from .= "Content-Type: text/html\n" : $from .= "Content-type: text/plain; charset=iso-8859-1\nContent-transfer-encoding: 8bit\n";

      $from .= "Date: ".date('r', time())."\n";
      $from .= "X-Priority: 3\n";
      $from .= "X-MSMail-Priority: Normal\nX-Mailer: PHP\nX-MimeOLE: Produced By Clanletter\n";

      return sendmail($email, $betreff, $text, $from);
      }

   }

//Email mit Anhang
function mail_att($to,$subject,$message,$format,$anhang)
   {
   global $config;
   if($format == "html") $format = "html";
   else $format = "plain";

   $mime_boundary = "-----=" . md5(uniqid(mt_rand(), 1));

   $header  ="From:".$config['name']."<".$config['email'].">\n";
   if($config['email_antwort'] != "") $header .= "Reply-To: ".$config['email_antwort']."\n";
   $header .= "Message-ID: <".md5(uniqid(time()))."@".$_SERVER['SERVER_NAME'].">\n";

   $header.= "MIME-Version: 1.0\r\n";
   $header.= "Content-Type: multipart/mixed;\r\n";
   $header.= " boundary=\"".$mime_boundary."\"\r\n";

   $content = "This is a multi-part message in MIME format.\r\n\r\n";
   $content.= "--".$mime_boundary."\r\n";
   $content.= "Content-Type: text/".$format." charset=\"iso-8859-1\"\r\n";
   $content.= "Content-Transfer-Encoding: 8bit\r\n\r\n";
   $content.= $message."\r\n";

   foreach($anhang AS $dat)
      {
      $content.= "--".$mime_boundary."\r\n";
      $content.= "Content-Disposition: attachment;\r\n";
      $content.= "\tfilename=\"".$dat['name']."\";\r\n";
      $content.= "Content-Length: .".$dat['size'].";\r\n";
      $content.= "Content-Type: ".$dat['type']."; name=\"".$dat['name']."\"\r\n";
      $content.= "Content-Transfer-Encoding: base64\r\n\r\n";
      $content.= $dat['data']."\r\n";
      }
   $content .= "--".$mime_boundary."--";

   return sendmail($to, $subject, $content, $header);
   }

function weiterleitung($url)
   {
   @header ("Location: $url\r\nP3P: CP=\"CAO PSA OUR\"");
   echo "
   <a href=\"$url\">Weiter</a>
   <meta http-equiv=\"refresh\" content=\"0; URL=$url\">
   ";

   exit;
   }



if(!function_exists("file_get_contents"))
   {
   function file_get_contents($file)
      {
      return implode("",file($file));
      }
   }




function sendmail($to, $subject, $msg, $header)
   {
   global $config;
   if($config['use_smtp'] == "1" AND !empty($config['smtp_host']))
      {
      if(!smtpmail($to,$subject,$msg,$header))
         die("Fehler beim Versenden der Email per SMTP");


      return true;
      }

   return @mail($to,$subject,$msg,$header);
   }


function umlaute($text)
   {
   $text = str_replace(chr(228),"&auml;",$text);
   $text = str_replace(chr(246),"&ouml;",$text);
   $text = str_replace(chr(252),"&uuml;",$text);

   $text = str_replace(chr(196),"&Auml;",$text);
   $text = str_replace(chr(215),"&Ouml;",$text);
   $text = str_replace(chr(220),"&Uuml;",$text);

   $text = str_replace(chr(223),"&szlig;",$text);
   #$text = str_replace(chr(34),"&quot;",$text);
   #$text = str_replace(chr(38),"&amp;",$text);

   #$text = str_replace("<","&lt;",$text);
   #$text = str_replace(">","&gt;",$text);

   return $text;
   }

function reumlaute($text)
   {
   $text = str_replace("&auml;",chr(228),$text);
   $text = str_replace("&ouml;",chr(246),$text);
   $text = str_replace("&uuml;",chr(252),$text);

   $text = str_replace("&Auml;",chr(196),$text);
   $text = str_replace("&Ouml;",chr(215),$text);
   $text = str_replace("&Uuml;",chr(220),$text);

   $text = str_replace("&szlig;",chr(223),$text);
   #$text = str_replace("&quot;",chr(34),$text);
   #$text = str_replace("&amp;",chr(38),$text);

   #$text = str_replace("&lt;","<",$text);
   #$text = str_replace("&gt;",">",$text);

   return $text;
   }



function template($name)
   {
   global $templatedb;

   $abfrage = "SELECT `value` FROM `$templatedb` WHERE `name` LIKE '$name'";
   $ergebnis = mysql_query($abfrage);
   $row = mysql_fetch_row($ergebnis);

   return addslashes($row[0]);

   }


/***************************************************************************
 *                              smtp.php
 *                       -------------------
 *   begin                : Wed May 09 2001
 *   copyright            : (C) 2001 The phpBB Group
 *   email                : support@phpbb.com
 *
 *   ******************** modified for Clanletter 2.0  *********************
 *
 *   $Id: smtp.php,v 1.16.2.9 2003/07/18 16:34:01 acydburn Exp $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

//
// This function has been modified as provided
// by SirSir to allow multiline responses when
// using SMTP Extensions
//

function server_parse($socket, $response, $line = __LINE__)
{
   $server_response = "";
   while (substr($server_response, 3, 1) != ' ')
      if (!($server_response = fgets($socket, 256)))
         return false;



   if (!(substr($server_response, 0, 3) == $response))
        return false;

   return true;
}


// Replacement or substitute for PHP's mail command
function smtpmail($mail_to, $subject, $message, $headers = '')
{
   global $config,$rand_array;

   $cc = $bcc = $server_response = "";

   // Fix any bare linefeeds in the message to make it RFC821 Compliant.
   $message = preg_replace("#(?<!\r)\n#si", "\r\n", $message);

   if ($headers != '')
   {
      if (is_array($headers))
      {
         if (sizeof($headers) > 1)
         {
            $headers = join("\n", $headers);
         }
         else
         {
            $headers = $headers[0];
         }
      }
      $headers = chop($headers);

      // Make sure there are no bare linefeeds in the headers
      $headers = preg_replace('#(?<!\r)\n#si', "\r\n", $headers);

      // Ok this is rather confusing all things considered,
      // but we have to grab bcc and cc headers and treat them differently
      // Something we really didn't take into consideration originally
      $header_array = explode("\r\n", $headers);
      @reset($header_array);

      $headers = '';
      while(list(, $header) = each($header_array))
      {
         if (preg_match('#^cc:#si', $header))
         {
            $cc = preg_replace('#^cc:(.*)#si', '\1', $header);
         }
         else if (preg_match('#^bcc:#si', $header))
         {
            $bcc = preg_replace('#^bcc:(.*)#si', '\1', $header);
            $header = '';
         }
         $headers .= ($header != '') ? $header . "\r\n" : '';
      }

      $headers = chop($headers);
      $cc = explode(', ', $cc);
      $bcc = explode(', ', $bcc);
   }

   if (trim($subject) == '')
      $subject = "Newsletter";



   // Ok we have error checked as much as we can to this point let's get on
   // it already.
   if( !$socket = fsockopen($config['smtp_host'], 25, $errno, $errstr, 20) )
      die("SMTP-Fehler: Verbindung zum Host (<i>".$config['smtp_host']."</i>) fehlgeschalgen");



   // Wait for reply
   if(!server_parse($socket, "220", __LINE__))
      die("SMTP-Fehler: Keine Antwort vom Host (<i>".$config['smtp_host']."</i>)");


   if(!empty($config['smtp_password'])) {
      include_once("xtea.inc.php");
      $smtp_password = xtea_decrypt($config['smtp_password'],$rand_array);
   } else
      $smtp_password = "";


   // Do we want to use AUTH?, send RFC2554 EHLO, else send RFC821 HELO
   // This improved as provided by SirSir to accomodate
   if( !empty($config['smtp_username']) AND !empty($smtp_password) )
   {

      fputs($socket, "EHLO " . $config['smtp_host'] . "\r\n");
      if(!server_parse($socket, "250", __LINE__))
           die("SMTP-Fehler: Fehler bei der Verbindung zum Host (<i>".$config['smtp_host']."</i>)");


      fputs($socket, "AUTH LOGIN\r\n");
      if(!server_parse($socket, "334", __LINE__))
         die("SMTP-Fehler: Fehler bei der Verbindung zum Host (<i>".$config['smtp_host']."</i>)");

      fputs($socket, base64_encode($config['smtp_username']) . "\r\n");
      if(!server_parse($socket, "334", __LINE__))
         die("SMTP-Fehler: Benutzername (<i>".$config['smtp_username']."</i>) nicht akzeptiert");

      fputs($socket, base64_encode($smtp_password) . "\r\n");
      if(!server_parse($socket, "235", __LINE__))
         die("SMTP-Fehler: Benutzername/Passwort nicht akzeptiert");
   }
   else
   {
      fputs($socket, "HELO " . $config['smtp_host'] . "\r\n");
      if(!server_parse($socket, "250", __LINE__))
         die("SMTP-Fehler: Verbindung fehlgeschalgen, evt. verlangt Host Benutzername und Passwort");
   }


   // From this point onward most server response codes should be 250
   // Specify who the mail is from....
   fputs($socket, "MAIL FROM: <" . $config['email'] . ">\r\n");
   if(!server_parse($socket, "250", __LINE__))
      die("SMTP-Fehler: Das Email-Konto (<i>".$config['email']."</i>) exitsiert nicht auf dem Host");

   // Specify each user to send to and build to header.
   $to_header = '';


   // Add an additional bit of error checking to the To field.
   $mail_to = (trim($mail_to) == '') ? 'Undisclosed-recipients:;' : trim($mail_to);
   if (preg_match('#[^ ]+\@[^ ]+#', $mail_to))
   {
      fputs($socket, "RCPT TO: <$mail_to>\r\n");
      if(!server_parse($socket, "250", __LINE__))
         return true;
   }


   // Ok now we tell the server we are ready to start sending data
   fputs($socket, "DATA\r\n");

   // This is the last response code we look for until the end of the message.
   if(!server_parse($socket, "354", __LINE__))
      die("SMTP-Fehler: Daten&uuml;bertragung konnte nicht gestartet werden.");

   // Send the Subject Line...
   fputs($socket, "Subject: $subject\r\n");

   // Now the To Header.
   fputs($socket, "To: $mail_to\r\n");

   // Now any custom headers....
   fputs($socket, "$headers\r\n\r\n");

   // Ok now we are ready for the message...
   fputs($socket, "$message\r\n");

   // Ok the all the ingredients are mixed in let's cook this puppy...
   fputs($socket, ".\r\n");
   if(!server_parse($socket, "250", __LINE__))
      die("SMTP-Fehler: Email konnte nicht &uuml;bertragen werden");


   // Now tell the server we are done and close the socket...
   fputs($socket, "QUIT\r\n");
   fclose($socket);

   return true;
}

?>